class History < ApplicationRecord
  belongs_to :user
  has_many :history_songs
  has_many :songs, through: :history_songs

  def add_song(song_id)
    if history_songs.exists?(song_id: song_id)
      history_songs.find_by(song_id: song_id).touch
    else
      if history_songs.count >= 500
        oldest = history_songs.order(updated_at: :asc).limit(1)[0]
        oldest.update(song_id: song_id)
      else
        history_songs.create(song_id: song_id)
      end
    end
  end
end
